using System.Windows;
using System.Windows.Documents;
using PatentAssistant.ViewModels;
using PatentAssistant.Utils;

namespace PatentAssistant
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private MainViewModel _viewModel;

        public MainWindow()
        {
            InitializeComponent();
            
            // 获取ViewModel实例
            _viewModel = (MainViewModel)DataContext;
            
            // 设置RichTextBox的Document
            MainTextBox.Document = _viewModel.MainDocument;
            
            // 监听Document变化
            _viewModel.PropertyChanged += ViewModel_PropertyChanged;
            
            // 设置获取选中文本的委托
            _viewModel.GetSelectedTextDelegate = GetSelectedText;
            _viewModel.ReplaceSelectedTextDelegate = ReplaceSelectedText;
        }

        private void ViewModel_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == nameof(MainViewModel.MainDocument))
            {
                // 确保UI线程更新
                Dispatcher.Invoke(() =>
                {
                    MainTextBox.Document = _viewModel.MainDocument;
                });
            }
        }

        /// <summary>
        /// 获取RichTextBox中选中的文本
        /// </summary>
        private string GetSelectedText()
        {
            if (MainTextBox.Selection.Text.Length > 0)
            {
                return MainTextBox.Selection.Text;
            }
            return string.Empty;
        }

        /// <summary>
        /// 替换RichTextBox中选中的文本
        /// </summary>
        private void ReplaceSelectedText(string newText)
        {
            if (MainTextBox.Selection.Text.Length > 0)
            {
                MainTextBox.Selection.Text = newText;
            }
        }
    }
} 